package com.we.flink.userlabelplatform.tag;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

import com.alibaba.fastjson.JSONObject;
import com.we.flink.userlabelplatform.table.TableHfqUserStrategy;

public class TagHfqUserStrategy {
    public long uid;
    public int update_time;
    public int user_random_map_id;

    public TagHfqUserStrategy() {}

    public TagHfqUserStrategy(long uid, int update_time, int user_random_map_id) {
        this.uid = uid;
        this.update_time = update_time;
        this.user_random_map_id = user_random_map_id;
    }

    public static TagHfqUserStrategy init(long uid) {
        return new TagHfqUserStrategy(uid, 0, -1);
    }

    public static SingleOutputStreamOperator<String> getFlatMapStream(
            StreamTableEnvironment tableEnv, StreamExecutionEnvironment env) {

        Table tableRes = tableEnv.sqlQuery(TableHfqUserStrategy.QUERYSQL);
        DataStream<Tuple2<Boolean, TableHfqUserStrategy>> inputStream =
                tableEnv.toRetractStream(tableRes, TableHfqUserStrategy.class);

        SingleOutputStreamOperator<String> out =
                inputStream
                        .filter(
                                new FilterFunction<Tuple2<Boolean, TableHfqUserStrategy>>() {
                                    @Override
                                    public boolean filter(
                                            Tuple2<Boolean, TableHfqUserStrategy> value)
                                            throws Exception {
                                        return value.f0;
                                    }
                                })
                        .uid("TagHfqUserStrategy-filter")
                        .keyBy(
                                new KeySelector<Tuple2<Boolean, TableHfqUserStrategy>, Long>() {
                                    @Override
                                    public Long getKey(Tuple2<Boolean, TableHfqUserStrategy> value)
                                            throws Exception {
                                        return value.f1.getUid();
                                    }
                                })
                        .flatMap(
                                new RichFlatMapFunction<
                                        Tuple2<Boolean, TableHfqUserStrategy>, String>() {
                                    ValueState<TagHfqUserStrategy> hfqUserStrategyTagVState;

                                    @Override
                                    public void open(Configuration parameters) throws Exception {
                                        hfqUserStrategyTagVState =
                                                getRuntimeContext()
                                                        .getState(
                                                                new ValueStateDescriptor<
                                                                        TagHfqUserStrategy>(
                                                                        "hfqUserStrategyTagVState",
                                                                        TagHfqUserStrategy.class));
                                    }

                                    @Override
                                    public void flatMap(
                                            Tuple2<Boolean, TableHfqUserStrategy> value,
                                            Collector<String> out)
                                            throws Exception {
                                        long uid = value.f1.getUid();
                                        int mapping_id = value.f1.getMapping_id();
                                        int update_time =
                                                (int) (value.f1.getUpdate_time().getTime() / 1000);

                                        TagHfqUserStrategy tmpState =
                                                hfqUserStrategyTagVState.value();
                                        TagHfqUserStrategy curState =
                                                tmpState == null
                                                        ? TagHfqUserStrategy.init(uid)
                                                        : tmpState;

                                        if (update_time > curState.getUpdate_time()) {
                                            if (mapping_id != curState.getUser_random_map_id()) {
                                                curState.update_time = update_time;
                                                curState.user_random_map_id = mapping_id;

                                                JSONObject jsonObject = new JSONObject();
                                                jsonObject.put("uid", uid);
                                                jsonObject.put("user_random_map_id", mapping_id);

                                                hfqUserStrategyTagVState.update(curState);
                                                out.collect(jsonObject.toString());
                                            }
                                        }
                                    }
                                });
        return out;
    }

    public long getUid() {
        return uid;
    }

    public int getUpdate_time() {
        return update_time;
    }

    public int getUser_random_map_id() {
        return user_random_map_id;
    }

    @Override
    public String toString() {
        return "TagHfqUserStrategy{"
                + "uid="
                + uid
                + ", update_time="
                + update_time
                + ", user_random_map_id="
                + user_random_map_id
                + '}';
    }
}
